package com.gxj.study.shopdemo.test;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.gxj.study.shopdemo.R;

import java.util.List;

/**
 * Created by 祥杰 on 2016/8/5.
 */

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private List<String> mDatas;
    private LayoutInflater mInflater;
    private OnItemClickListener listener;

    public MyAdapter(List<String> datas) {
        mDatas = datas;
    }

    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        mInflater = LayoutInflater.from(parent.getContext());
        View view = mInflater.inflate(R.layout.activity_swiperefresh_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
        holder.text.setText(mDatas.get(position));
    }

    @Override
    public int getItemCount() {
        return mDatas.size();
    }


    public void setListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    interface OnItemClickListener {
        void onClick(View v, int position, String city);
    }

    public void addData(int position, String city) {
        mDatas.add(position, city);
        notifyItemInserted(position);
    }

    public void removeDate(int position) {
        mDatas.remove(position);
        notifyItemRemoved(position);
    }

    public void notifyItemChange(int start, int itemCount) {
        notifyItemRangeChanged(start,itemCount);
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        private TextView text;

        public ViewHolder(View itemView) {
            super(itemView);
            text = (TextView) itemView.findViewById(R.id.text);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(listener != null){
                        listener.onClick(view,getLayoutPosition(),mDatas.get(getLayoutPosition()));
                    }
                }
            });
        }
    }
}